package com.clouds.wms.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class UploadFile {
	private Log log = LogFactory.getLog(getClass());
	private List<String> fileType;// 允许的文件类型(为空时，不做验证)
	private double fileSize;// 允许文件的大小(为0时不做限止)
	private List<String> fileShape;// 允许的文件长宽(为空时，不做验证)
	private int flag;// 文件的宽高的关系(0-不限制，1-大于等于，2-等于，3-小于等于)

	public static String attRootPath = SysParams.UPLOAD_FILE_PATH;// 上传根路径
	
	public static String SYSTEM_LINE = File.separator;// 系统反斜杠 linux / windows \\

	private int width;
	private int height;

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}

	public void init() {
		init(null, null, 81920, 0);// 80K
	}
	public void init(double fileSize) {
		init(null, null, fileSize, 0);
	}

	public void init(List<String> fileType, List<String> fileShapg) {
		init(fileType, fileShapg, 81920, 2);
	}
	
	public void init(List<String> fileType, double fileSize) {
		init(fileType, null, fileSize, 0);
	}

	/**
	 * 初始化文件的条件要求
	 * 
	 * @param fileType
	 * @param fileSize
	 * @param fileWidth
	 * @param fileHeight
	 */
	public void init(List<String> fileType, List<String> fileShap, double fileSize, int flag) {
		this.fileType = fileType;
		this.fileSize = fileSize;
		this.fileShape = fileShap;
		this.flag = flag;
	}

	public UploadFile() {}

	public List<Object> loading(CommonsMultipartFile file, String name)  {
		List<Object> errorList = new ArrayList<Object>();
		errorList = checkAll(file);
		if (errorList.size() <= 0) {
			try {
				String tempFileName = file.getOriginalFilename();
				log.info("已经获得上传文件的名字");
				if(name == null || name.equals("")) {
					tempFileName = Calendar.getInstance().getTimeInMillis() + tempFileName.substring(tempFileName.lastIndexOf("."));
				} else {
					tempFileName = name;
				}
				log.info("配置文件的虚拟路径");
				String path = attRootPath + SYSTEM_LINE + tempFileName;
				log.info("配置文件的虚拟路径");
				Function.mkdir(attRootPath);
				log.info("创建虚拟路径");
				File tempImg = new File(path);
				FileCopyUtils.copy(file.getBytes(), tempImg);
				log.info("上传文件");
			} catch (Exception ex) {
				throw new RuntimeException();
			}
		}
		return errorList;
	}
	
	public String load(CommonsMultipartFile file, String path){
		try {
			Function.mkdir(attRootPath);
			log.info("创建虚拟路径");
			File imgFile = new File(path);
			log.info("上传文件");
			FileCopyUtils.copy(file.getBytes(), imgFile);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException();
		}
		return path;
	}
	public String newLoad(CommonsMultipartFile file, String foldNamePath, String name){
		String path = "";
		try {
			String tempFileName = file.getOriginalFilename();//文件名称
			log.info("已经获得上传文件的名字");
			if (name == null || name.equals("")) {
				tempFileName = Calendar.getInstance().getTimeInMillis() + tempFileName.substring(tempFileName.lastIndexOf("."));
			} else {
				tempFileName = name;
			}
			log.info("配置文件的虚拟路径");
			path = attRootPath + SYSTEM_LINE + tempFileName;
			
			Function.mkdir(attRootPath);
			Function.mkdir(foldNamePath);
			
			log.info("创建虚拟路径");
			File imgFile = new File(path);
			log.info("上传文件");
			FileCopyUtils.copy(file.getBytes(), imgFile);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException();
		}
		return path;
	}

	public List<Object> loadToAnother(String url, CommonsMultipartFile file, String path, String name) {
		List<Object> errorList = new ArrayList<Object>();
		if(file != null) {
			errorList = checkAll(file);
		}
		if(errorList.size() <= 0) {
			try {
				String tempFileName = file.getOriginalFilename();
				if (name == null || name.equals("")) {
					tempFileName = Calendar.getInstance().getTimeInMillis() + tempFileName.substring(tempFileName.lastIndexOf("."));
				} else {
					tempFileName = name;
				}
				InputStream stream = file.getInputStream();
				URL anotherUrl = new URL(url);
				URLConnection connection = anotherUrl.openConnection();
				connection.setDoInput(true);
				connection.setDoOutput(true);
				connection.setUseCaches(false);
				connection.setDefaultUseCaches(false);
				connection.setRequestProperty("Content-Type", "application/octet-stream");
				ObjectOutputStream oos = new ObjectOutputStream(connection.getOutputStream());
				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
					oos.write(buffer, 0, bytesRead);
				}
				oos.flush();
			} catch (Exception ex) {
				throw new RuntimeException();
			}
		}
		return errorList;
	}

	public List<Object> checkAll(CommonsMultipartFile file) {
		List<Object> errorList = new ArrayList<Object>();
		if (!checkFileType(file)) {
			errorList.add("文件类型不匹配,只能为" + this.fileType);
		} else {
			if (!checkFileSize(file)) {
				errorList.add("文件大小不得大于" + new BigDecimal(this.fileSize).divide(new BigDecimal(1024), 1, BigDecimal.ROUND_DOWN).doubleValue() + "K");
			}
			if (!checkFileWH(file)) {
				String hw = "";
				if (this.flag == 1) {
					hw = "大于等于";
				} else if (this.flag == 2) {
					hw = "等于";
				} else if (this.flag == 3) {
					hw = "小于等于";
				}
				errorList.add("文件(宽*高)必须" + hw + this.fileShape);
			}
		}
		return errorList;
	}

	/**
	 * 只检测文件类型,文件大小
	 * @param file
	 * @return
	 */
	public List<Object> checkTypeAndSize(CommonsMultipartFile file) {
		List<Object> errorList = new ArrayList<Object>();
		if (!checkFileType(file)) {
			errorList.add("文件类型不匹配,只能为" + this.fileType);
		} else {
			if (!checkFileSize(file)) {
				errorList.add("文件大小不得大于" + new BigDecimal(this.fileSize).divide(new BigDecimal(1024), 1, BigDecimal.ROUND_DOWN).doubleValue() + "K");
			}
		}
		return errorList;
	}

	/**
	 * 只检测文件类型,文件大小
	 * @param file
	 * @return
	 */
	public List<Object> checkTypeAndSize(String title, CommonsMultipartFile file) {
		List<Object> errorList = new ArrayList<Object>();
		if (!checkFileType(file)) {
			errorList.add(title+"文件类型不匹配,只能为" + this.fileType);
		} else {
			if (!checkFileSize(file)) {
				errorList.add(title+"文件大小不得大于" + new BigDecimal(this.fileSize).divide(new BigDecimal(1024), 1, BigDecimal.ROUND_DOWN).doubleValue() + "K");
			}
		}
		return errorList;
	}
	
	
	/**
	 * 验证文件的类型
	 * @param file
	 * @return
	 */
	public boolean checkFileType(CommonsMultipartFile file) {
		boolean flag = true;
		String extName = getFileExtName(file.getOriginalFilename());
		if (this.fileType != null && this.fileType.size() > 0 && !this.fileType.contains(extName)) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 验证文件的大小
	 * @param file
	 * @return
	 */
	public boolean checkFileSize(CommonsMultipartFile file) {
		boolean flag = true;
		if (this.fileSize > 0 && (file.getSize() > this.fileSize)) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 验证文件的长宽
	 * @param file
	 * @return
	 */
	public boolean checkFileWH(CommonsMultipartFile file) {
		boolean flag = true;
		try {
			int width = 0;
			int height = 0;
			BufferedImage bi = ImageIO.read(file.getInputStream());
			width = bi.getWidth();
			height = bi.getHeight();
			this.width = width;
			this.height = height;
			if (this.fileShape != null && this.fileShape.size() > 0) {
				if (this.flag == 1) {
					String wh = (String) this.fileShape.get(0);
					int wid = Integer.parseInt(wh.substring(0, wh.indexOf("*")));
					int hei = Integer.parseInt(wh.substring(wh.indexOf("*") + 1), wh.length());
					if (width < wid || height < hei) {
						flag = false;
					}
				} else if (this.flag == 2) {
					if (!this.fileShape.contains(width + "*" + height)) {
						flag = false;
					}
				} else if (this.flag == 3) {
					String wh = (String) this.fileShape.get(0);
					int wid = Integer.parseInt(wh.substring(0, wh.indexOf("*")));
					int hei = Integer.parseInt(wh.substring(wh.indexOf("*") + 1), wh.length());
					if (width > wid || height > hei) {
						flag = false;
					}
				}
			}
		} catch (IOException e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 取得指定文件的扩展名 如果没有扩展名，则返回null
	 * @param filename
	 * @return
	 */
	public String getFileExtName(String filename) {
		int i = filename.lastIndexOf('.');
		if (i == -1) {
			return null;
		} else {
			return filename.substring(i, filename.length()).toLowerCase();
		}
	}

}
